﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using thousandclear.Data;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Shop.Controllers
{
    public class GradesController :BaseController
    {
        // GET: Shop/Grades
        public ActionResult Index(string code, string state, string openid)
        {
            AppSetting setting = new AppSetting();

            string access_token = "";
            string UserName = "";
            string headImage = "";
            if (string.IsNullOrEmpty(openid))
            {
                var i = GetOpenId(code);
                openid = i.openid;
                access_token = i.access_token;


                if (string.IsNullOrEmpty(openid))
                {
                    Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                    return null;
                }
                var tt = GetUserInfo(openid, access_token);
                headImage = tt.headimgurl;
                UserName = tt.nickname;
                UtilNS.Util.WriteLog("UserName::" + UserName);
                UtilNS.Util.WriteLog("openid::" + openid);
            }

            using (var db = new qianjingEntities())
            {
                var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                if (customer == null)
                {
                    db.O_Customer.Add(new O_Customer
                    {
                        ocOpenid = openid,
                        ocNicName = UserName,
                        CreatedDate = DateTime.Now,
                        ocHeadImage = headImage,
                        RowStatus = 1,
                        ocGrades = 0,
                    });
                    db.SaveChanges();

                }
                else
                {
                    customer.ocHeadImage = headImage;
                    customer.ocNicName = UserName;
                    db.SaveChanges();
                }
                ViewBag.grades = customer.ocGrades;
            }

            ViewBag.OpenId = openid;
            ViewBag.State = state;
            ViewBag.Code = code;
            return View();

        }
    }
}